import { Provide } from '@midwayjs/core';
import { Repository } from 'typeorm';
import { FirmwareWristband } from '../../entity/firmware/firmware_wristband.entity';
import { FirmwareWristbandFile } from '@entity/firmware/firmwareWristbandFile.entity';
import { firmware_type } from '../../entity/enums';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { resBuild } from '@utils/resBuild';
@Provide()
export class FirmwareWristbandService {
  @InjectEntityModel(FirmwareWristband)
  firmwareWristbandRepo: Repository<FirmwareWristband>;

  @InjectEntityModel(FirmwareWristbandFile)
  firmwareWristbandFileRepo: Repository<FirmwareWristbandFile>;


  // 创建固件
  async createFirmware(
    name: string,
    version: string,
    firmware: firmware_type,
    path: string,
    desc?: string,
    raw?: boolean,
    fileid?: string
  ) {
    console.log('debug');
    // 如果提供了 fileid，则检查文件是否存在
    if (fileid) {
      const existingFile = await this.firmwareWristbandFileRepo.findOne({
        where: { fileid },
      });

      if (!existingFile) {
        console.log('文件不存在');
        throw new Error(`文件 ID ${fileid} 不存在，请先上传文件`);
      }
    }
    // 创建固件
    const firmwareVal = new FirmwareWristband();
    firmwareVal.name = name;
    firmwareVal.version = version;
    firmwareVal.firmware = firmware || firmware_type['gw-bin'];
    firmwareVal.path = path;
    firmwareVal.desc = desc || '';
    firmwareVal.date = new Date();
    firmwareVal.raw = raw || false;
    firmwareVal.fileid = fileid;
    firmwareVal.deleted = false;
    return await this.firmwareWristbandRepo.save(firmwareVal);
  }

  // 上传文件并存储文件信息到数据库
  async uploadFile(fileData: any, fileId, path) {
    // 生成文件 ID
    const fileRecord = new FirmwareWristbandFile();
    fileRecord.fileid = fileId; // 文件 ID 用于关联固件
    fileRecord.file_name = fileData.filename.trim();
    fileRecord.file_path = path;
    fileRecord.real_path = '';
    return await this.firmwareWristbandFileRepo.save(fileRecord);
  }

  // 关联固件和文件
  async linkFileToFirmware(firmwareId: number, fileId: string) {
    const firmware = await this.firmwareWristbandRepo.findOne({
      where: { id: firmwareId },
    });
    if (!firmware) {
      throw new Error('固件不存在');
    }

    firmware.fileid = fileId;
    return await this.firmwareWristbandRepo.save(firmware);
  }

  // 获取所有固件
  async getAllFirmware(name?: string, version?: string) {
    const query = this.firmwareWristbandRepo
      .createQueryBuilder('firmware')
      .where('firmware.deleted != :deleted', { deleted: true });

    if (name) {
      query.andWhere('firmware.name LIKE :name', { name: `%${name}%` });
    }

    if (version) {
      query.andWhere('firmware.version LIKE :version', {
        version: `%${version}%`,
      });
    }

    return query.getMany();
  }

   // 根据 fileid 获取固件firmwareWristbandFileRepo 中对应的path
   async getFirmwareFileById(fileid: string) {
    let path =  await this.firmwareWristbandFileRepo.findOne({
      where: { fileid }
    });
    console.log('path', path.file_path)
    return {
      path:path.file_path,
      name: path.file_name
    };
  }

  // 根据 ID 获取固件
  async getFirmwareById(firmwareId: number) {
    return await this.firmwareWristbandRepo.findOne({
      where: { id: firmwareId },
      relations: ['file'], // 关联文件信息
    });
  }

  // async updateProfile(user: UpdateProfileDto) {
  //   const myUserInfo: UserEntity = this.ctx.session.userInfo;
  //   await this.userEntity.update(
  //     {
  //       userId: myUserInfo.userId,
  //     },
  //     {
  //       ...user,
  //     }
  //   );
  //   return resBuild.success();
  // }
  // **更新固件**
  async updateFirmware(id: number, updateData: Partial<FirmwareWristband>) {
    const firmware = await this.getFirmwareById(id);
    // 判断该id存不存在
    if (!firmware) return resBuild.fail('固件不存在！');

    // Object.assign(firmware, updateData);
    firmware.date = new Date(); // 更新修改时间
    console.log('111111111111', updateData);
    try{
      await this.firmwareWristbandRepo.update({ id: id }, { ...updateData });

    }catch(err){
      console.log('原因', err)
    }

    return resBuild.success();
  }

  // **删除固件**
  async deleteFirmware(id: number) {
    const firmware = await this.getFirmwareById(id);
    // 判断该id存不存在
    if (!firmware) return resBuild.fail('固件不存在！');
    firmware.date = new Date(); // 更新修改时间
    await this.firmwareWristbandRepo.update({ id: id }, { deleted: true });
    // await this.firmwareWristbandRepo.update({ id: id }, { deleted: true });
    return resBuild.success();
  }

  // 删除固件文件
  async deleteFile(fileid: string) {
    await this.firmwareWristbandFileRepo.update(
      { fileid: fileid },
      { deleted: true }
    );
    return resBuild.success();
  }

  // 模拟下发固件到手环
  async sendFirmwareToWristband(
    gatewayId: string,
    firmware: FirmwareWristband
  ) {
    console.log(
      `✅ 正在向网关 ${gatewayId} 下发固件：`,
      firmware.name,
      `版本: ${firmware.version}`
    );
    // 这里可以调用 MQTT / WebSocket / HTTP API，将固件推送到手环
  }
}
